// app.js
const { musicsKV } = require('./cabin.config')
App({
  onLaunch() {
    // 获取系统信息
    wx.getSystemInfo({
      success: e => {
        this.globalData.StatusBar = e.statusBarHeight;
        let custom = wx.getMenuButtonBoundingClientRect();
        this.globalData.Custom = custom;  
        this.globalData.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
      }
    })
    this.promiseMusic()
  },
  transformData (res) {
    let temAry = []
    for (let index = 0, len = res.length; index < len; index++) {
      const { data, info } = res[index];
      let mp3s = [];
      let lrcs = [];
      let coverInfo = {}
      data.map(item => {
        if (item.extensionName === "lrc") {
          lrcs.push(item)
        }
        if (item.extensionName === "mp3") {
          mp3s.push(item)
        }
        if (item.extensionName === "jpg") {
          coverInfo = {
            ...item,
            ...info
          }
        }
      })
      temAry.push({
        mp3s,
        lrcs, 
        coverInfo
      })
    }
    this.globalData.musicList =  temAry;
    if(this.musicCallback && typeof this.musicCallback === 'function') {
      this.musicCallback()
      console.log('musicCallback')
    }
  },
  promiseMusic () {
    let promiseArr = [];
    for (let index = 0, len = musicsKV.length; index < len; index++) {
      const api = musicsKV[index];
      let promise = new Promise((resolve, reject) => {
        wx.request({
          url: api.api,
          success: function(res) {
            const { code, data, message} =  res.data
            if (code === 200) {
              resolve({
                data: data.spaceEntities,
                info: api
              })
            } else {
              reject(message || '失败')
            }
          },
          fail: function (error) {
            reject(error)
          }
        })
      })
      promiseArr.push(promise)
    }
    Promise.all(promiseArr).then((res) => {
      this.transformData(res || [])
    })
  },
  globalData: {
  }
})
